import { User } from "@/entities/User";
import { initORM } from "@/utils";
import { NextApiRequest, NextApiResponse } from "next";

export async function getCurrentUser(req: NextApiRequest) {
  const userId = req.headers.userid;
  const em = await initORM();
  const user = await em.findOne(User, Number(userId));

  return user;
}

export async function getUser(req: NextApiRequest) {
  const userId = req.query.userid;
  const em = await initORM();
  const user = await em.findOne(User, Number(userId));

  return user;
}

export async function updateUser(
  req: NextApiRequest,
  res: NextApiResponse<APIRes>
) {
  const { role, disabled, id } = req.body ?? {};
  if (!id) {
    res.status(400).json({
      success: false,
      data: {},
      message: "Missing user id",
    });
    return;
  }

  req.query.userid = id;
  const targetUser = await getUser(req);
  if (!targetUser) {
    res.status(400).json({
      success: false,
      data: {},
      message: "User not found",
    });
    return;
  }

  let message = "";
  if (role !== undefined) {
    targetUser.role = role;
    message = `Change role to ${role === 1 ? "admin" : "normal"}  success`;
  }

  if (disabled !== undefined) {
    targetUser.disabled = disabled;
    message = `Change status to ${disabled ? "disabled" : "active"}  success`;
  }

  const em = await initORM();
  await em.persistAndFlush(targetUser);

  res.status(200).json({
    success: true,
    data: {},
    message,
  });
}

export async function getUsers(
  req: NextApiRequest,
  res: NextApiResponse<APIRes>
) {
  const em = await initORM();
  const isAll = req.query.all;
  const users = isAll
    ? await em.findAll(User, {})
    : await em.find(User, req.query);

  const curUser = await getCurrentUser(req);
  // allows jack to access all users
  if (curUser?.role !== 1 && curUser?.email !== "jack.pan@newaim.com.au") {
    res.status(403).json({
      success: false,
      data: {},
      message: "Forbidden, You are not admin",
    });

    return;
  }

  res
    .status(200)
    .json({ success: true, data: users, message: "Query users success" });
}

export async function getAllUsersSimply(req: NextApiRequest) {
  const em = await initORM();
  const users = await em.findAll(User, {});

  return {
    success: true,
    data: users,
    message: "Query users success",
  };
}

export async function createUser(
  req: NextApiRequest,
  res: NextApiResponse<APIRes>
) {
  const em = await initORM();
  const user = await em.create(User, req.body);
  await em.persistAndFlush(user);

  res.status(200).json({ success: true, data: {}, message: "User created" });
}
